package com.example.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.file.entity.FileInfo;
import com.example.file.service.IFileInfoService;
import com.example.file.util.FileUtil;

import com.example.user.entity.User;
import com.example.util.PageResult;
import com.example.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 贾明祯
 * @ClassName FileController
 * @Date 2020/9/10 13:59
 * @Introduce
 */
@Controller
@RequestMapping("/sysFile")
public class FileController {
    private String PREFIX = "view/sysfile/";

    @Autowired
    private IFileInfoService fileInfoService;

    @PostMapping("/uploadFile")
    @ResponseBody
    public Map<String,Object> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        FileInfo fileInfo = new FileInfo();
        try{

            if (!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                long ss= file.getSize();
                String  fileSuffix = fileName.substring(fileName.lastIndexOf("."));
                fileInfo.setFileSuffix(fileSuffix);
                fileInfo.setFileSize(ss+"");
                fileInfo.setFilePath(FileUtil.getFilePath());
                fileInfo.setFileName(fileName);
                File dir = new File(FileUtil.getFilePath(),fileName);
                if(!dir.exists()){
                    file.transferTo(dir);
                    map.put("code",200);
                    map.put("msg","上传成功");
                    map.put("data",fileInfo);
                    return map;
                }else {
                    dir.delete();
                    file.transferTo(dir);
                    map.put("code",200);
                    map.put("msg","文件从新上传成功");
                    map.put("data",fileInfo);
                    return map;
                }

            }}catch (Exception e){
            System.out.println(e);
        }
        map.put("code",500);
        map.put("msg","文件上传失败");
        return map;
    }

    @RequestMapping("/download/{fileCode}")
    public void download(@PathVariable(name = "fileCode") String fileCode,HttpServletResponse res, HttpServletRequest request) throws IOException {
        FileInfo fileInfo = fileInfoService.getById(fileCode);
        File file = new File(fileInfo.getFilePath()+fileInfo.getFileName());
        FileInputStream fileInputStream = new FileInputStream(file);
        BufferedInputStream bfi = new BufferedInputStream(fileInputStream);
        res.reset();
        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/force-download");// 设置强制下载不打开
        res.setContentType("application/x-msdownload"); // 不同类型的文件对应不同的MIME类型 // 重点突出
        res.setContentType("application/octet-stream");
        // inline在浏览器中直接显示，不提示用户下载
        // attachment弹出对话框，提示用户进行下载保存本地
        // 默认为inline方式
        res.addHeader("Content-Disposition", "attachment;fileName=" +
                new String(file.getName().getBytes("gbk"), "iso8859-1"));// 设置文件名
        OutputStream os = res.getOutputStream();
        byte[] tempbytes = new byte[1024];
        int bytes = 0;
        int i =0;
        while ((bytes=bfi.read(tempbytes))!=-1){
            os.write(tempbytes,0,bytes);
        }
        bfi.close();
        fileInputStream.close();
    }

    /**
     * 跳转到文件表首页
     */
//    @RequiresPermissions("user:view")
    @RequestMapping("")
    public String index(Model model, HttpServletRequest request) {
        return PREFIX + "sysFile";
    }

    /**
     * 跳转到添加文件表
     */
    @RequestMapping("/sysFileadd")
    public String toAdd(Model model,HttpServletRequest request) {
        return PREFIX + "sysFile_add";
    }

    /**
     * 跳转到修改文件表
     */
    @RequestMapping("/sysFileupdate/{sysFileId}")
    public String toUpdate(Model model,HttpServletRequest request,@PathVariable("sysFileId") String sysFileId) {
        model.addAttribute("sysFile", JSONObject.toJSON(fileInfoService.getById(sysFileId)));
        return PREFIX + "sysFile_edit";
    }


    /**
     * 文件表详情
     */
    @RequestMapping("/detail/{fileId}")
    public String toDetail(@PathVariable("fileId") String fileId, Model model,HttpServletRequest request) {
        model.addAttribute("sysFile",JSONObject.toJSON(fileInfoService.getById(fileId)));
        return PREFIX + "sysFile_view";
    }

    /**
     * 获取文件表列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public PageResult<FileInfo> list(Integer page, Integer limit, FileInfo sysFile, String condition, Model model, HttpServletRequest request) {
        return fileInfoService.listPage(page,limit,sysFile);
    }


    /**
     * 新增文件表
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Result add(FileInfo sysFile) {
        if (fileInfoService.save(sysFile)) {
            return Result.success(200,"添加成功");
        } else {
            return Result.error(500,"添加失败");
        }
    }

    /**
     * 删除文件表
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result delete(@RequestParam String sysFileId) {
        FileInfo fileInfo = fileInfoService.getById(sysFileId);
        File file = new File(fileInfo.getFilePath()+fileInfo.getFileName());
        file.delete();
        if (fileInfoService.removeById(sysFileId)) {
            return Result.success(200,"删除成功");
        } else {
            return Result.error(500,"删除失败");
        }
    }

    /**
     * 逻辑删除文件表
     */
    @RequestMapping(value = "/logicDelete")
    @ResponseBody
    public Result logicDelete(@RequestParam String sysFileId) {
        FileInfo sysFile=fileInfoService.getById(sysFileId);
        if (fileInfoService.logicDelete(sysFile)) {
            return Result.success(200,"删除成功");
        } else {
            return Result.error(500,"删除失败");
        }
    }


    /**
     * 修改文件表
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Result update(FileInfo sysFile) {
        if (fileInfoService.updateById(sysFile)) {
            return Result.success(200,"修改成功");
        } else {
            return Result.error(500,"删除失败");
        }
    }


    @RequestMapping("/batchDelete")
    @ResponseBody
    public Result batchDelete(String departIds) {
        System.out.println(departIds);
        List<String> lis = Arrays.asList(departIds.split(","));
        if (fileInfoService.removeByIds(lis)) {
            return Result.success(200,"删除成功");
        }
        return Result.error(500,"删除失败");
    }

    @RequestMapping("/updateFilename")
    @ResponseBody
    public Result updateFilename(String fileId,String newName) {
        if(fileInfoService.updateFilename(fileId,newName)){
            return Result.success(200,"修改成功");
        }
        return Result.error(500,"修改失败");
    }
}
